﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

using AnOtherBlog.Core;


namespace AnOtherBlog.AJAX.Admin.Posts
{
	public partial class PostEdit : AnOtherBlog.Core.Web.AdminBasePage
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			//base.LblMsg = this.lblMsg;

			if (!Page.IsPostBack)
			{
				BindCategories();

				string sId = Util.GetParameter("id");
				if (!string.IsNullOrEmpty(sId))
				{
					BindPost(new Guid(sId));
				}
				BindPostList();
			}

			btnCategoryAdd.Click += new EventHandler(btnCategoryAdd_Click);
			btnSave.Click += new EventHandler(btnSave_Click);

		}

		/// <summary>
		/// Triggered after Click
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
		void btnCategoryAdd_Click(object sender, EventArgs e)
		{
			try
			{
				if (!Page.IsValid)
					throw new InvalidOperationException("Alguna de las validaciones no se cumple.");

				Category category = new Category(txtCategoryName.Text, string.Empty);
				category.Save();
				ListItem listItem = new ListItem(Server.HtmlEncode(category.CategoryName), category.CategoryID.ToString());
				listItem.Selected = true;
				cblCategories.Items.Add(listItem);
			}
			catch (Exception ex)
			{
				MsgSetCritical(ex.Message);
			}
		}
		/// <summary>
		/// Triggered after Click
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
		void btnSave_Click(object sender, EventArgs e)
		{
			try
			{
				if (!Page.IsValid)
					throw new InvalidOperationException("Alguna de las validaciones no se cumple.");

				Post post;
				string sId = Util.GetParameter("id");
				if (!string.IsNullOrEmpty(sId))
				{
					post = Post.Load(new Guid(sId));
				}
				else
				{
					post = new Post();
				}

				if (string.IsNullOrEmpty(txtPostContent.Text))
				{
					txtPostContent.Text = "[Nada]";
				}

				post.Title = txtTitle.Text;
				post.PostContent = txtPostContent.Text;
				post.Description = txtDescription.Text;
				// TODO: Hay que incorporar el modulo de autores !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
				post.Author = "yo";

				post.IsCommentEnabled = cbIsCommentEnabled.Checked;
				post.IsPublished = cbIsPublished.Checked;


				post.Categories.Clear();

				Category category = null;
				foreach (ListItem listItem in cblCategories.Items)
				{
					if (listItem.Selected)
					{
						category = Blog.Current.CategoryFind(new Guid(listItem.Value));
						// Se supone que está pero por las dudas ...
						if (category != null)
						{
							post.Categories.Add(category);
						}
					}
				}

				post.Save();

				BindPostList();
				MsgSet("Publicación Grabada Satisfactoriamente");
			}
			catch (Exception ex)
			{
				MsgSetCritical(ex.Message);
			}
		}

		/// <summary>
		/// Enlaza todas las categorías con el checkboxlist
		/// </summary>
		private void BindCategories()
		{
			foreach(Category category in Blog.Current.Categories)
			{
				cblCategories.Items.Add(new ListItem(Server.HtmlEncode(category.CategoryName), category.CategoryID.ToString()));
			}
		}

		/// <summary>
		/// Enlaza una publicación con los controles de edición
		/// </summary>
		/// <param name="Id">Identificador de la publicación</param>
		private void BindPost(Guid Id)
		{
			Post post = Post.Load(Id);

			txtTitle.Text = post.Title;
			txtPostContent.Text = post.PostContent;
			txtDescription.Text = post.Description;
			txtSlug.Text = post.Slug;

			cbIsCommentEnabled.Checked = post.IsCommentEnabled;
			cbIsPublished.Checked = post.IsPublished;

			// Fija las categorías asignadas al post
			foreach (Category category in post.Categories)
			{
				ListItem listItem = cblCategories.Items.FindByValue(category.CategoryID.ToString());
				if (listItem != null)
					listItem.Selected = true;
			}

		}

		// TODO: Esto no debe estar (ahora lo necesito para ver las publicaciones)
		private void BindPostList()
		{
            Blog.Current.ReLoadPosts();
			foreach (Post post in Blog.Current.Posts)
			{
				HtmlGenericControl li = new HtmlGenericControl("li");
				HtmlAnchor a = new HtmlAnchor();
				a.HRef = "?id=" + post.PostID.ToString();
				a.InnerHtml = post.Title;
				li.Controls.Add(a);
				ulPosts.Controls.Add(li);
			}
		}

	}
}
